<!--
 * @author guojiteng
法律咨询新增/编辑
 -->
<template>
  <section class="law-consult-edit">
    <section class="law-consult-edit-title">法律咨询{{ type==='u'?'编辑':'创建' }}</section>
    <section ref="lawconsult" v-loading="loading" class="law-consult-edit-main">
      <ul>
        <li v-for="(item, index) in list" :key="index">
          <section class="top">
            <span class="type" :class="{'q': item.questionAnswer == '1', 'a': item.questionAnswer == '2'}">{{
              item.questionAnswer == '1' ? '问' : '答'
            }}</span>
            <el-button v-if="index!==0" size="small" type="primary" icon="el-icon-delete" @click="removeItem(item,index)" />
          </section>
          <p v-if="index===0" class="tag">
            <span class="key">问题标签：</span>
            <span class="val">
              <el-select
                v-model="tagValue"
                style="width: 100%"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="选择或手动输入标签"
              >
                <el-option
                  v-for="item in dict.FLJXLX"
                  :key="item.dictValue"
                  :label="item.dictName"
                  :value="item.dictName"
                />
              </el-select>
            </span>
          </p>
          <p class="time">
            <span class="key">{{ item.questionAnswer == '1' ? '咨询时间' : '回复时间' }}：  </span>
            <span class="val">
              <el-date-picker
                v-model="item.consultTime"
                type="datetime"
                placeholder="选择日期时间"
              />
              <el-tag v-if="item.timeError" type="danger">{{ item.questionAnswer == '1' ? '咨询时间' : '回复时间' }}不能早于上一条数据</el-tag>
            </span></p>
          <p class="desc">
            <span class="key">{{ item.questionAnswer == '1' ? '咨询内容' : '回复内容' }}： </span>
            <span class="val">
              <el-input
                v-model="item.commentContent"
                type="textarea"
                :autosize="{ minRows: 4 }"
                placeholder="请输入内容"
              />
            </span>
          </p>
          <section style="padding-left: 100px">
            <update-img :key="time" :img-data="item.imgData" :index="index" @imgShowView="imgShowView" @getImgId="getImgId" />
          </section>
          <el-button type="primary" style="padding: 10px 30px; margin: 10px 10px 10px 100px;" @click="questioningOrAnswer(item,index,1)">追问</el-button>
          <el-button type="primary" style="padding: 10px 30px; margin: 10px 10px 10px 0px;" @click="questioningOrAnswer(item,index,2)">追答</el-button>
        </li>
      </ul>
    </section>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="[PreviewUrl]"
    />
    <section class="law-consult-edit-footer">
      <el-button style="padding: 10px 30px;" @click="handleBack()">返 回</el-button>
      <el-button type="primary" style="padding: 10px 30px;" @click="handleSubmit(0)">保存</el-button>
      <el-button type="primary" style="padding: 10px 30px;" @click="handleSubmit(1)">保存并发布</el-button>
    </section>
  </section>
</template>
<script>
import { query, del, insertItem, getDictByCode } from './../api'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import defaultImg from '../images/default.png'
import UpdateImg from '../components/updateImg'
export default {
  name: 'LawConsultEdit',
  components: { ElImageViewer, UpdateImg },
  data() {
    return {
      defaultSrc: 'this.src="' + defaultImg + '"',
      PreviewUrl: '',
      showViewer: false,
      loading: false,
      view: '/API-DOCUMENT/document/file/download?id=',
      list: [],
      id: '',
      type: '', // 页面类型  c：创建 u：修改
      time: new Date().getTime(),
      t: '', // 回复的类型
      tagValue: [],
      options: [{
        value: '婚姻家庭',
        label: '婚姻家庭'
      }, {
        value: '财产纠纷',
        label: '财产纠纷'
      }, {
        value: '继承',
        label: '继承'
      }],
      dict: {
        FLJXLX: []
      }
    }
  },
  created() {
    this.type = this.$route.query.pt
    for (const key in this.dict) {
      this.getDict(key)
    }
    if (this.type === 'u' || this.type === 'copy') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      } else {
        this.id = this.$route.query.i
        this.t = this.$route.query.t
        this.getList()
      }
    } else {
      this.initList()// 初始化问答
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = (response.data.data && response.data.data.length > 0) ? response.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 打开大图
    imgShowView(item) {
      this.PreviewUrl = item
      this.showViewer = true
    },
    // 关闭预览
    closeViewer() {
      this.showViewer = false
    },
    /*
    * 判断时间是否按顺序
    * */
    checkTime() {
      for (let i = 0; i < this.list.length; i++) {
        if (i !== 0 && this.list[i].consultTime < this.list[i - 1].consultTime) {
          this.list[i].timeError = true
          this.$message.error(`${this.list[i].questionAnswer == '1' ? '咨询' : '回复'} 时间不正确，请检查`)
          return false
        } else {
          this.list[i].timeError = false
        }
      }
      return true
    },
    async handleSubmit(type) {
      if (!this.checkTime()) {
        return
      }
      if (this.type === 'u') {
        const delResult = await this.delAll()
        if (delResult.data.code !== '200') {
          this.$message.error(delResult.data.msg || '数据删除失败！')
          return
        }
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      let flag = true
      for (let i = 0; i < this.list.length; i++) {
        const item = this.list[i]
        if (i !== 0) {
          const parent = this.list[i - 1]
          item.commentParentId = parent.id
          item.commentRootId = parent.commentRootId
        } else {
          item.labels = this.tagValue.join(',')
          item.isPush = type
          item.copyId = this.id
        }
        const res = await this.insertItemFun(item)
        if (res.data.code !== '200') {
          this.$message.error(res.data.msg || '数据添加失败！')
          loading.close()
          flag = false
          break
        }
        Object.assign(this.list[i], res.data.data)
      }
      loading.close()
      if (flag) {
        this.$message.success('操作成功！')
        this.$router.push({ path: this.$filterPath('index'), query: { t: '3' }})
      }
    },
    delAll() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        del({ id: this.id }).then((res) => {
          loading.close()
          resolve(res)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    insertItemFun(item) {
      return new Promise((resolve, reject) => {
        delete item.imgData
        delete item.bid
        delete item.crtTime
        delete item.id
        delete item.timeError
        item.consultTime = new Date(item.consultTime).Format('yyyy-MM-dd hh:mm:ss')
        insertItem(item).then((res) => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    /*
    * 设置图片
    * */
    getImgId(obj) {
      this.list[obj.index].userImgs = obj.imgs.join(',')
    },
    /*
    * 删除追问或者追答
    * */
    removeItem(item, index) {
      this.$confirm(`确认删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.list.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 追问/追答
     * */
    questioningOrAnswer(item, index, type) {
      const obj = {
        commentContent: '',
        userImgs: '',
        consultativeType: 'FLZX',
        commentParentId: '',
        commentRootId: '',
        consultTime: this.list[index].consultTime,
        questionAnswer: type,
        imgData: [],
        timeError: false
      }
      this.list.splice(index + 1, 0, obj)
      this.time = new Date().getTime()
    },

    /**
     * 初始化问答
     * */
    initList() {
      const ask = {
        commentContent: '',
        userImgs: '',
        consultativeType: 'FLZX',
        consultTime: new Date(),
        questionAnswer: '1',
        labels: '',
        imgData: [],
        timeError: false
      }
      this.list.push(ask)
      const answer = {
        commentContent: '',
        userImgs: '',
        consultativeType: 'FLZX',
        commentParentId: '',
        commentRootId: '',
        consultTime: new Date().getTime() + 1000,
        questionAnswer: 2,
        imgData: [],
        timeError: false
      }
      this.list.push(answer)
    },
    handleBack() {
      this.$router.push({ path: this.$filterPath('index'), query: { t: this.$route.query.t }})
    },
    getList() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        const url = this.t === '3' ? '/backend/excellentConsultLog/getData' : '/backend/consultativeLog/get'
        const obj = {}
        if (this.t === '3') {
          obj.id = this.id
        } else {
          obj.consultativeType = 'FLZX'
          obj.commentRootId = this.id
        }
        query(obj, url
        ).then(res => {
          loading.close()
          if (res.data.data) {
            const list = res.data.data
            if (list[0].labels) {
              this.tagValue = list[0].labels.split(',')
            }
            res.data.data.forEach(item => {
              item.imgData = item.userImgs ? item.userImgs.split(',') : []
              item.timeError = false
            })
          }
          this.list = res.data.data || []
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>
<style lang="scss">

.law-consult-edit {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .law-consult-edit-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .law-consult-edit-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: auto;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    ul {
      margin: 0;
      padding: 0;
      list-style: none;

      li {
        border: 1px solid #e5e5e5;
        border-radius: 5px;
        padding: 0 10px;
        margin-bottom: 10px;
        box-shadow: 0 0 10px #e2e2e2;

        .top {
          height: 50px;
          line-height: 50px;

          .type {
            font-size: 14px;
            color: #fff;
            padding: 5px;

            &.q {
              background-color: #00A1D9;
            }

            &.a {
              background-color: red;
            }
          }

          .name {
            font-size: 14px;
            color: #606266;
            margin-left: 10px;
          }

          .el-button {
            float: right;
            margin-top: 10px;
          }
        }

        .time,.tag,
        .desc {
          font-size: 14px;
          padding-left: 30px;
          display: flex;
          .key{
            width: 70px;
            color: #606266;
          }
          .val{
            flex: 1;
          }
        }

        .images {
          padding-left: 100px;
          display: flex;
          align-items: center;
          flex-wrap: wrap;
        .img-item{
            width: 100px;
            height: 100px;
            margin-right: 10px;
            margin-bottom: 10px;
            position: relative;
          >img{
            width: 100%;
            height: 100%;
          }
          .img-close{
            width: 25px;
            height: 25px;
            position: absolute;
            right: -10px;
            top: 0;
            >img{
              width: 100%;
              height: 100%;
            }
          }
        }
        }
      }
    }
  }

  .law-consult-edit-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
